'use client';

import React, { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import {
  Box,
  Typography,
  Container,
  Grid,
  Card,
  CardContent,
  CardActions,
  Button,
  TextField,
  InputAdornment,
  CircularProgress,
  Pagination,
  Chip,
  Divider,
  Alert,
  Paper,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
} from '@mui/material';
import SearchIcon from '@mui/icons-material/Search';
import BusinessIcon from '@mui/icons-material/Business';
import WorkIcon from '@mui/icons-material/Work';
import LocationOnIcon from '@mui/icons-material/LocationOn';
import AttachMoneyIcon from '@mui/icons-material/AttachMoney';
import Navbar from '@/components/Navbar';
import ResumeSubmitForm from '@/components/recruitment/ResumeSubmitForm';
import { useRouter } from 'next/navigation';

// 将职位数据按公司分组
const groupJobsByCompany = (jobs: any[]) => {
  console.log('开始分组职位数据, 总数:', jobs.length);
  const companiesMap = new Map();

  jobs.forEach(job => {
    const companyId = job.company_id;
    console.log('处理职位:', { id: job.id, title: job.title, companyId, companyName: job.company_name });

    if (!companyId) {
      console.warn('跳过没有company_id的职位:', job.id);
      return;
    }

    if (!companiesMap.has(companyId)) {
      console.log('创建新公司分组:', { companyId, companyName: job.company_name });
      companiesMap.set(companyId, {
        id: companyId,
        name: job.company_name || '未命名公司',
        industry: job.company_industry || '未指定',
        size: job.company_size || '未指定',
        location: job.location || '未指定', // 使用职位的location代替公司的location
        positions: []
      });
    }

    companiesMap.get(companyId).positions.push({
      id: job.id,
      title: job.title,
      salary: job.salary_range,
      experience: job.experience,
      education: job.education,
      location: job.location,
      job_type: job.job_type
    });
  });

  const result = Array.from(companiesMap.values());
  console.log('分组结果:', {
    companiesCount: result.length,
    companies: result.map(c => ({ id: c.id, name: c.name, positionsCount: c.positions.length }))
  });
  return result;
};

export default function RecruitmentPage() {
  const [searchTerm, setSearchTerm] = useState('');
  const [companies, setCompanies] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [isCompanyAdmin, setIsCompanyAdmin] = useState(false);
  const [showResumeForm, setShowResumeForm] = useState(false);
  const [selectedPosition, setSelectedPosition] = useState<any>(null);
  const [error, setError] = useState('');
  const [loginDialogOpen, setLoginDialogOpen] = useState(false);
  const router = useRouter();

  // 获取招聘信息
  useEffect(() => {
    const fetchJobs = async () => {
      try {
        setLoading(true);
        setError('');

        console.log('开始获取招聘信息');
        const response = await fetch(`/api/recruitment/get-jobs?page=1&limit=50&status=active`);

        if (!response.ok) {
          throw new Error('获取招聘信息失败');
        }

        const data = await response.json();
        console.log('获取到的招聘数据:', {
          jobsCount: data.jobs?.length || 0,
          pagination: data.pagination
        });

        if (data.jobs && data.jobs.length > 0) {
          console.log('第一个职位数据示例:', {
            id: data.jobs[0].id,
            title: data.jobs[0].title,
            company_id: data.jobs[0].company_id,
            company_name: data.jobs[0].company_name
          });
        }

        const groupedCompanies = groupJobsByCompany(data.jobs || []);
        console.log('分组后的公司数量:', groupedCompanies.length);
        setCompanies(groupedCompanies);
        setTotalPages(data.pagination?.totalPages || 1);
      } catch (err) {
        console.error('获取招聘信息失败:', err);
        setError((err as Error).message);
      } finally {
        setLoading(false);
      }
    };

    fetchJobs();

    // 检查用户是否登录及企业身份
    const token = localStorage.getItem('token');
    setIsLoggedIn(!!token);

    // 如果登录了，检查是否为企业负责人
    if (token) {
      const checkCompanyAdmin = async () => {
        try {
          const response = await fetch('/api/profile', {
            headers: {
              'Authorization': `Bearer ${token}`
            }
          });

          if (response.ok) {
            const userData = await response.json();
            setIsCompanyAdmin(userData.is_company_admin || false);
          } else if (response.status === 401) {
            // 如果是401错误，不要自动登出，只记录错误
            console.error('获取用户信息失败: 未授权');
          } else {
            console.error('获取用户信息失败:', response.status);
          }
        } catch (error) {
          console.error('获取用户信息失败:', error);
        }
      };

      checkCompanyAdmin();
    }
  }, []);

  // 处理搜索
  const handleSearch = async () => {
    try {
      setLoading(true);
      setError('');

      const response = await fetch(`/api/recruitment/search-jobs?keyword=${encodeURIComponent(searchTerm)}&page=1&limit=50`);

      if (!response.ok) {
        throw new Error('搜索招聘信息失败');
      }

      const data = await response.json();
      const groupedCompanies = groupJobsByCompany(data.jobs || []);
      setCompanies(groupedCompanies);
      setTotalPages(data.pagination?.totalPages || 1);
      setPage(1);
    } catch (err) {
      console.error('搜索招聘信息失败:', err);
      setError((err as Error).message);
    } finally {
      setLoading(false);
    }
  };

  // 处理页面变化
  const handlePageChange = (event: React.ChangeEvent<unknown>, value: number) => {
    setPage(value);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // 处理投递简历
  const handleSubmitResume = (company: any, position: any) => {
    if (!isLoggedIn) {
      // 如果未登录，显示登录对话框
      localStorage.setItem('redirectAfterLogin', '/recruitment');
      setLoginDialogOpen(true);
      return;
    }

    setSelectedPosition({
      companyId: company.id,
      companyName: company.name,
      positionId: position.id,
      positionName: position.title,
    });

    setShowResumeForm(true);
  };

  // 处理登录对话框关闭
  const handleCloseLoginDialog = () => {
    setLoginDialogOpen(false);
  };

  // 跳转到登录页面
  const handleGoToLogin = () => {
    router.push('/login?redirect=/recruitment');
  };

  // 关闭简历表单
  const handleCloseResumeForm = () => {
    setShowResumeForm(false);
    setSelectedPosition(null);
  };

  // 简历提交成功
  const handleSubmitSuccess = () => {
    setTimeout(() => {
      setShowResumeForm(false);
      setSelectedPosition(null);
    }, 1500);
  };

  // 每页显示的公司数量
  const itemsPerPage = 5;
  const paginatedCompanies = companies.slice(
    (page - 1) * itemsPerPage,
    page * itemsPerPage
  );

  return (
    <Box sx={{ minHeight: '100vh', bgcolor: '#f5f5f5' }}>
      <Box
        sx={{
          bgcolor: 'primary.main',
          color: 'white',
          py: 8,
          textAlign: 'center',
          backgroundImage: 'linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url(https://source.unsplash.com/random/1600x900/?office)',
          backgroundSize: 'cover',
          backgroundPosition: 'center',
        }}
      >
        <Container maxWidth="lg">
          <Typography variant="h3" component="h1" gutterBottom>
            企业招聘直通车
          </Typography>
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', mb: 4 }}>
            <Typography variant="h6" sx={{ mr: 2 }}>
              选择校友企业，直接投递简历，获取面试机会
            </Typography>

            {isCompanyAdmin && (
              <Button
                variant="contained"
                color="success"
                component={Link}
                href="/recruitment/post"
                startIcon={<BusinessIcon />}
                sx={{ ml: 2 }}
              >
                发布招聘公告
              </Button>
            )}
          </Box>

          <Box
            component="form"
            onSubmit={(e) => {
              e.preventDefault();
              handleSearch();
            }}
            sx={{
              display: 'flex',
              maxWidth: 600,
              mx: 'auto',
              bgcolor: 'white',
              borderRadius: 2,
              overflow: 'hidden',
              boxShadow: 3,
            }}
          >
            <TextField
              fullWidth
              placeholder="搜索公司或职位..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <SearchIcon />
                  </InputAdornment>
                ),
                sx: { borderRadius: 0 }
              }}
              variant="outlined"
              sx={{ '& fieldset': { border: 'none' } }}
            />
            <Button
              type="submit"
              variant="contained"
              sx={{ borderRadius: 0, px: 4 }}
              disabled={loading}
            >
              {loading ? <CircularProgress size={24} /> : '搜索'}
            </Button>
          </Box>
        </Container>
      </Box>

      <Container maxWidth="lg" sx={{ py: 4 }}>
        {error && (
          <Alert severity="error" sx={{ mb: 3 }}>
            {error}
          </Alert>
        )}

        {loading && companies.length === 0 ? (
          <Box sx={{ textAlign: 'center', py: 4 }}>
            <CircularProgress />
            <Typography variant="h6" sx={{ mt: 2 }}>
              正在加载招聘信息...
            </Typography>
          </Box>
        ) : companies.length === 0 ? (
          <Paper sx={{ p: 4, textAlign: 'center' }}>
            <Typography variant="h6" color="text.secondary">
              没有找到匹配的公司或职位
            </Typography>
            <Button
              variant="outlined"
              sx={{ mt: 2 }}
              onClick={() => {
                setSearchTerm('');
                handleSearch();
              }}
            >
              查看所有企业
            </Button>
          </Paper>
        ) : (
          <>
            <Typography variant="h5" component="h2" gutterBottom>
              企业列表
            </Typography>

            {paginatedCompanies.map((company) => (
              <Card
                key={company.id}
                sx={{
                  mb: 3,
                  boxShadow: 2,
                  borderRadius: '8px',
                  overflow: 'hidden',
                  transition: 'all 0.3s ease',
                  '&:hover': {
                    boxShadow: 4
                  }
                }}
              >
                <CardContent sx={{ p: 3 }}>
                  <Grid container spacing={2}>
                    <Grid item xs={12}>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                        <Typography variant="h6" component="h3" sx={{ fontWeight: 'bold', color: 'primary.main' }}>
                          {company.name}
                        </Typography>
                        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
                          <Chip
                            icon={<BusinessIcon fontSize="small" />}
                            label={company.industry}
                            size="small"
                            variant="outlined"
                          />
                          <Chip
                            icon={<WorkIcon fontSize="small" />}
                            label={company.size}
                            size="small"
                            variant="outlined"
                          />
                          <Chip
                            icon={<LocationOnIcon fontSize="small" />}
                            label={company.location}
                            size="small"
                            variant="outlined"
                          />
                        </Box>
                      </Box>

                      <Divider sx={{ my: 2 }} />

                      <Typography variant="subtitle1" sx={{ mb: 2, fontWeight: 500, color: 'text.primary' }}>
                        招聘职位
                      </Typography>

                      <Grid container spacing={2}>
                        {company.positions.map((position: any) => (
                          <Grid item xs={12} md={6} key={position.id}>
                            <Card
                              variant="outlined"
                              sx={{
                                height: '100%',
                                transition: 'all 0.3s ease',
                                '&:hover': {
                                  transform: 'translateY(-4px)',
                                  boxShadow: 3,
                                  borderColor: 'primary.main'
                                }
                              }}
                            >
                              <CardContent sx={{ pb: 1 }}>
                                <Typography variant="h6" component="h4" sx={{ fontWeight: 500 }}>
                                  {position.title}
                                </Typography>
                                <Box sx={{ display: 'flex', alignItems: 'center', mt: 1 }}>
                                  <AttachMoneyIcon fontSize="small" color="primary" />
                                  <Typography variant="body2" sx={{ ml: 0.5, fontWeight: 500, color: 'success.main' }}>
                                    {position.salary}
                                  </Typography>
                                </Box>
                                <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                                  {position.experience} | {position.education} | {position.location}
                                </Typography>
                              </CardContent>
                              <CardActions>
                                <Button
                                  size="small"
                                  variant="contained"
                                  onClick={() => handleSubmitResume(company, position)}
                                  sx={{
                                    borderRadius: '4px',
                                    textTransform: 'none',
                                    boxShadow: 1,
                                    '&:hover': {
                                      boxShadow: 2
                                    }
                                  }}
                                >
                                  投递简历
                                </Button>
                              </CardActions>
                            </Card>
                          </Grid>
                        ))}
                      </Grid>
                    </Grid>
                  </Grid>
                </CardContent>
              </Card>
            ))}

            {companies.length > itemsPerPage && (
              <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4, mb: 2 }}>
                <Pagination
                  count={Math.ceil(companies.length / itemsPerPage)}
                  page={page}
                  onChange={handlePageChange}
                  color="primary"
                  size="large"
                  showFirstButton
                  showLastButton
                  sx={{
                    '& .MuiPaginationItem-root': {
                      borderRadius: '8px',
                    },
                    '& .Mui-selected': {
                      fontWeight: 'bold',
                    }
                  }}
                />
              </Box>
            )}
          </>
        )}
      </Container>

      {showResumeForm && selectedPosition && (
        <ResumeSubmitForm
          companyId={selectedPosition.companyId}
          companyName={selectedPosition.companyName}
          positionId={selectedPosition.positionId}
          positionName={selectedPosition.positionName}
          onClose={handleCloseResumeForm}
          onSubmitSuccess={handleSubmitSuccess}
        />
      )}

      {/* 登录提示对话框 */}
      <Dialog
        open={loginDialogOpen}
        onClose={handleCloseLoginDialog}
      >
        <DialogTitle>需要登录</DialogTitle>
        <DialogContent>
          <DialogContentText>
            您需要登录后才能投递简历
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseLoginDialog}>取消</Button>
          <Button 
            onClick={handleGoToLogin} 
            variant="contained" 
            color="primary"
          >
            去登录
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}
